import axios from 'axios';
import type { AxiosRequestConfig, AxiosInstance, AxiosResponse } from 'axios';
// import Cookies from 'js-cookie';
import storage from 'store';
// import { error } from '../methods';
import route from '../../router';
import { Notify } from 'quasar';
import { GlobalStore } from '@/stores';

const router = route();
class VAxios {
  private options: AxiosRequestConfig;
  private axiosInstance: AxiosInstance;

  constructor(options: AxiosRequestConfig) {
    this.options = options;
    this.axiosInstance = axios.create(this.options);
    this.setupInterceptors();
  }

  errorEvent(err: Error) {
    console.log('err', err);
  }

  ServerError(res: AxiosResponse<any>) {
    const globalStore = GlobalStore();
    if (res.data && res.data.code === -2) {
      // error({ message: '登录失效' })
      console.log('登录失效');
      Notify.create({
        color: 'white',
        textColor: 'negative',
        icon: 'cancel',
        position: 'top',
        message: 'token失效,请重新登录',
      });
      globalStore.clearLogin();
      router.push('/login');
      setTimeout(() => {
        location.reload();
      }, 1500);
    } else if (res.data && res.data.code !== 200) {
      Notify.create({
        color: 'white',
        textColor: 'negative',
        icon: 'cancel',
        position: 'top',
        message: res.data.msg,
      });
    }
  }

  private setupInterceptors() {
    this.axiosInstance.interceptors.request.use((req: AxiosRequestConfig) => {
      const token = storage.get('Access-Token');
      if (token) {
        req.headers['Authorization'] = 'Bearer ' + token;
      }
      return req;
    }, this.errorEvent);

    this.axiosInstance.interceptors.response.use((res: AxiosResponse<any>) => {
      this.ServerError(res);

      return res.data;
    }, this.errorEvent);
  }

  request(opt: AxiosRequestConfig) {
    return new Promise((resolve, reject) => {
      this.axiosInstance
        .request<any, AxiosResponse>(opt)
        .then((res: AxiosResponse) => {
          resolve(res);
        })
        .catch((err: Error) => {
          reject([null, err]);
        });
    });
  }
}

const env = process.env;
const prod = env.NODE_ENV === 'production';

const AxiosTemplate = new VAxios({
  timeout: 15 * 1000,
  baseURL: prod ? env.VUE_APP_API_BASE_TEMPLATE_URL : '/template',
});

const AxiosAccount = new VAxios({
  timeout: 15 * 1000,
  baseURL: prod ? env.VUE_APP_API_URL + '/back' : env.VUE_APP_API_URL + '/back',
  // baseURL: 'http://test.yuanqi.3qma.com',
});

export { AxiosTemplate, AxiosAccount };
